package com.jar.netty_demo.Netty.task;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 聊天室：服务端
 */
public class ServerChat {
    private static final int PORT = 9999;

    private void run() throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class) //为什么要用这个类
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//TCP会实现监控连接是否有效
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                    //每个客户对应自己的SocketChannel，可以放到集合中去
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //向pipeline中加入解码器
                            pipeline.addLast("decode", new StringDecoder());
                            //向pipeline中加入编码器
                            pipeline.addLast("encode", new StringEncoder());
                            //加入自己的业务处理
                            pipeline.addLast(new ServerChatHandle());
                            //加入一个重复的处理器，检验执行流程，这个处理器的read方法不会执行，因为前面那个已经执行过了
//                            pipeline.addLast(new ServerChatHandle1());

                        }
                    });
            System.out.println("服务端已经启动。。。。");
            //绑定端口
            ChannelFuture sync = serverBootstrap.bind(PORT).sync();
            //监听关闭
            sync.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ServerChat().run();
    }
}
